#include "Mysql.h"

#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlResult>
#include <QDebug>

Mysql::Mysql(QObject *parent)
    :QObject(parent)
{
    m_MySqlInfo["HostName"] = "127.0.0.1";
    m_MySqlInfo["DatabaseName"] = "database";
    m_MySqlInfo["UserName"] = "root";
    m_MySqlInfo["Password"] = "root";
    m_MySqlInfo["Port"] = "3306";

    m_MySqlInfo["ConnectionName"] = "LMS_MYSQL";
    m_MySqlInfo["ConnectOptions"] = "MYSQL_OPT_RECONNECT=1;";
}

Mysql::~Mysql()
{
    close();
}

void Mysql::close()
{
    //qDebug() << "status4:" << m_db.isOpen() << m_db.isValid();
    if(m_db.isOpen())
    {
        m_db.close();
        //qDebug() << "status5:" << m_db.isOpen() << m_db.isValid();
    }

    if(m_db.isValid())
    {
        //m_db = QSqlDatabase::addDatabase("","");
        //QSqlDatabase::removeDatabase(m_MySqlInfo["ConnectionName"]);
        //qDebug() << "status6:" << m_db.isOpen() << m_db.isValid();
    }
    //qDebug() << "status7:" << m_db.isOpen() << m_db.isValid();
}

bool Mysql::connectDB()
{
    qDebug() << "m_db:" << m_db.driverName() << m_db.connectionName();
    if(m_db.isOpen())
        return true;

    QString strWillRemove = "";
    if(m_db.isValid())      //已经有链接
    {
        if(m_db.connectionName() != m_MySqlInfo["ConnectionName"])  //如果链接名不同,则准备删除旧的
            strWillRemove = m_db.connectionName();
    }
    else        //没有链接过
        m_db = QSqlDatabase::addDatabase("QMYSQL3",m_MySqlInfo["ConnectionName"]);

    if(!strWillRemove.isEmpty())
    {
        m_db = QSqlDatabase::addDatabase("QMYSQL3",m_MySqlInfo["ConnectionName"]);

        QSqlDatabase::removeDatabase(strWillRemove);
        strWillRemove = "";
    }

    //qDebug() << "status1:" << m_db.isOpen() << m_db.isValid();

    //if(QSqlDatabase::contains(m_MySqlInfo["ConnectionName"]))
    //    return true;
    //if(m_db.isOpen() && m_db.isValid())
    //    return true;

    m_db.setHostName(m_MySqlInfo["HostName"]);
    m_db.setDatabaseName(m_MySqlInfo["DatabaseName"]);
    m_db.setUserName(m_MySqlInfo["UserName"]);
    m_db.setPassword(m_MySqlInfo["Password"]);
    m_db.setPort(m_MySqlInfo["Port"].toInt());
    m_db.setConnectOptions(m_MySqlInfo["ConnectOptions"]);   //断开后重新连接!!!
    qDebug()<<"MySQL Option:"<<m_db.connectOptions();

    if(!m_db.open())
    {
        emit s_Critical("[!MySQL]数据库连接错误:" + m_db.lastError().text());
        //qDebug() << "status2:" << m_db.isOpen() << m_db.isValid();
        m_db.close();
        //qDebug() << "status22:" << m_db.isOpen() << m_db.isValid();
        //QSqlDatabase::removeDatabase(m_MySqlInfo["ConnectionName"]);
        //qDebug() << "status222:" << m_db.isOpen() << m_db.isValid();
        return false;
    }
    else
    {
        //qDebug() << "status3:" << m_db.isOpen() << m_db.isValid();
        qDebug() << "Database Connection Successful";
    }

    return true;
}


